using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace Managers
{
    public static class CommentManager
    {
        public static DAL.IPRelationship CurrentIPRelationship
        {
            get
            {
                DAL.User user = Managers.UserLoginManager.CurrentUser;

                // attempting to retrieve IPRelationship from cookie
                DAL.IPRelationship relationship = DAL.IPRelationships.Item(RelationshipID);
                if (relationship == null)
                {
                    // attempting to retrieve IPRelationship by UserID
                    if (user != null)
                    {
                        relationship = DAL.IPRelationships.GetByUser(user);
                    }

                    // if both attempts above fail, create a new IPRelationship for this user
                    if (relationship == null)
                    {
                        relationship = new DAL.IPRelationship();
                        DAL.IPRelationships.Add(relationship);
                    }
                }
                else
                {
                    if (relationship.User == null)
                    {
                        if (user != null)
                        {
                            DAL.IPRelationships.UpdateTrackingByRelationshipAndUser(ref relationship, user);                            
                            if (user.HasPermissions(DAL.User.UserStatus.Moderator))
                            {
                                relationship.Banned = false;
                            }
                            relationship.User = user;
                            DAL.IPRelationships.Save(relationship);
                        }
                    }
                }

                RelationshipID = relationship.ID;
                return relationship;
            }
        }

        private static long RelationshipID
        {
            get
            {
                string ipr = DAL.CookieManager.TryGetCookie("ipr", "0");
                long id;
                if (Int64.TryParse(ipr, out id))
                {
                    return id;
                }
                else
                {
                    return 0;
                }
            }
            set
            {
                DAL.CookieManager.SetCookie("ipr", value.ToString(), DateTime.Now.AddYears(1));
            }
        }
    }
}